package com.lyx.lib_viewonclick;

import android.app.Application;
import android.util.Log;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONObject;

import java.util.Map;

@Keep
public class SensorsDataAPI {

    private final String TAG = this.getClass().getSimpleName();
    public static final String SDK_VERSION = "1.0.0";

    private static volatile SensorsDataAPI instance;

    private static Map<String, Object> mDeviceInfo;
    private String mDeviceId;

    @Keep
    public static SensorsDataAPI init(Application application) {
        if (instance == null) {
            synchronized (SensorsDataAPI.class) {
                if (instance == null) {
                    instance = new SensorsDataAPI(application);
                }
            }
        }
        return instance;
    }

    @Keep
    public static SensorsDataAPI getInstance() {
        return instance;
    }

    private SensorsDataAPI(Application application) {
        mDeviceId = DeviceUtil.getAndroidID(application.getApplicationContext());
        mDeviceInfo = DeviceUtil.getDeviceInfo(application.getApplicationContext());
        SensorsDataPrivate.registerActivityLifecycleCallbacks(application);
    }

    /**
     * Track 事件
     *
     * @param eventName  String 事件名称
     * @param properties JSONObject 事件属性
     */
    @Keep
    public void track(@NonNull final String eventName, @Nullable JSONObject properties) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("event", eventName);
            jsonObject.put("device_id", mDeviceId);
            JSONObject sendProperties = new JSONObject(mDeviceInfo);
            if (properties != null) {
                JsonHelper.mergeJSONObject(properties, sendProperties);
            }
            jsonObject.put("properties", sendProperties);
            jsonObject.put("time", System.currentTimeMillis());
            Log.i(TAG, JsonHelper.formatJson(jsonObject.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
